﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using amis6_api.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Dapper;
using amis6_api.Model;
using amis6_api.Dto;
using amis6_api.Utils;
using amis6_api.Service;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace amis6_api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class AMIS6Controller : ControllerBase
    {
        private readonly IHttpContextAccessor _accessor;

        public AMIS6Controller(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        /// <summary>
        /// 获取权限内全宗
        /// </summary>
        /// <returns>{"code":1,"msg":"OK","data":[{"parent":{"fonds_ID":"2bdab619-f8ee-4f49-9f31-516f4be405b6","fonds_Level":1,"fonds_Father":null,"fonds_Code":"888","fonds_Name":"静安区教育局","fonds_Order":0,"fonds_JGH":null,"fonds_JGMLH":null,"fonds_Remark":null},"children":[{"parent":{"fonds_ID":"3f0e5c8a-35a8-49b3-ac60-f7ddc7093b00","fonds_Level":1,"fonds_Father":"2bdab619-f8ee-4f49-9f31-516f4be405b6","fonds_Code":"XZGJZX","fonds_Name":"上海市新中高级中学","fonds_Order":0,"fonds_JGH":null,"fonds_JGMLH":null,"fonds_Remark":null},"children":null}]},{"parent":{"fonds_ID":"58bdfdc3-daef-4d51-8481-ab0b23916169","fonds_Level":1,"fonds_Father":null,"fonds_Code":"1","fonds_Name":"1","fonds_Order":0,"fonds_JGH":null,"fonds_JGMLH":null,"fonds_Remark":null},"children":null}]}</returns>
        [HttpGet("getFonds")]
        public BaseResult<List<FondsDto>> Get()
        {
            var user = JwtUtils.LoginUser(_accessor.HttpContext);
            using var conn = DbFactory.Db();
            //筛选全宗权限
            UserFondsService userFondsService = new UserFondsService();
            var list = userFondsService.GetUserFonds(user);
            return BaseResult<List<FondsDto>>.OK(list);
        }

        /// <summary>
        /// 获取根据全宗id获取对应formmodel
        /// </summary>
        /// <param name="fondsId">全宗id</param>
        /// <returns></returns>
        [HttpGet("getFormModel/{fondsId}")]
        public BaseResult<List<FormModel>> GetFormModel(Guid fondsId)
        {
            var user = JwtUtils.LoginUser(_accessor.HttpContext);
            using var conn = DbFactory.Db();
            //string sql = "SELECT * FROM t_Fonds_Class a join t_Class b on a.Class_ID=b.Class_ID WHERE a.Fonds_ID=@id";
            //var classes = conn.Query<Clazz>(sql, new { id = id }).OrderBy(a => a.Class_Order).ToList();
            List<FormModel> list = new List<FormModel>();
            if (user.U_IsManager)
            {
                list = conn.Query<FormModel>(
                    "SELECT a.FM_ID,a.FM_OEName,a.FM_OCName,a.FM_Index,a.FC_ID FROM t_FormModel a left join t_Fonds_Class b on a.FC_ID=b.FC_ID WHERE b.Fonds_ID=@id",
                    new { id = fondsId }).OrderBy(a => a.FM_Index).ToList();
            }
            else
            {
                String uid = UserPermissionUtil.GetUserPermission(user.U_ID);
                Guid menuId = conn.QueryFirst<Guid>($"SELECT MNU_ID FROM t_Menus WHERE MNU_Caption = '档案管理'");
                string sql =
                    $"select a.* from t_FormModel a inner join (select left(GUP_ResourceID,36) id from T_UserTempMenu where [GU_GUID] in {uid} and MNU_Type='Instance_FormModel' and GUP_ResourceID like '%{menuId.ToString()}') b  on b.id=a.FM_ID inner join t_Fonds_Class c on a.FC_ID=c.FC_ID WHERE c.Fonds_ID='{fondsId}';";
                list = conn.Query<FormModel>(sql).ToList();
            }

            return BaseResult<List<FormModel>>.OK(list);
        }

        /// <summary>
        /// 根据fmid获取对面类型   0)以卷  1_以件
        /// </summary>
        /// <param name="fmId">formModelId</param>
        /// <returns></returns>
        [HttpGet("getFormModelType/{fmId}")]
        public BaseResult<int> GetFormModelType(Guid fmId)
        {
            var user = JwtUtils.LoginUser(_accessor.HttpContext);
            using var conn = DbFactory.Db();
            var relation = conn.Query<FormModelTable>("Select * from t_FormModel_Table a where a.FM_ID=@id", new { id = fmId }).OrderBy(a => a.FMT_Order).ToList();
            int type;
            switch (relation.Count)
            {
                case 1:
                    type = 1;
                    break;
                case 2:
                    type = relation.Any(a => a.FMT_IsFJ) ? 1 : 0;
                    break;
                default:
                    type = 0;
                    break;
            }

            return BaseResult<int>.OK(type);
        }


        /// <summary>
        /// 根据fmid获取分类id
        /// </summary>
        /// <param name="id">FormModelID</param>
        /// <returns></returns>
        [HttpGet("getCatalog/{id}")]
        public BaseResult<List<CatalogDto>> GetCatalog(Guid id)
        {
            var user = JwtUtils.LoginUser(_accessor.HttpContext);
            using var conn = DbFactory.Db();
            List<Catalog> categories;
            if (user.U_IsManager)
            {
                categories = conn.Query<Catalog>("Select * from t_Catalog a where a.FM_ID=@id", new { id = id }).OrderBy(a => a.Catalog_Order).ToList();
            }
            else
            {
                String uid = UserPermissionUtil.GetUserPermission(user.U_ID);
                Guid menuId = conn.QueryFirst<Guid>($"SELECT MNU_ID FROM t_Menus WHERE MNU_Caption = '档案管理'");
                categories = conn.Query<Catalog>(
                    $"select a.*from t_Catalog a left join (select right(GUP_ResourceID, 36) id from T_UserTempMenu where [GU_GUID] in {uid} and MNU_Type = 'Catalog' and GUP_ResourceID like '%{menuId.ToString()}') b on b.id = a.Catalog_ID where a.FM_ID = '{id}';").ToList();
            }

            List<CatalogDto> catalogs = RecursiveUtil.GetCatalogDtos(categories);
            return BaseResult<List<CatalogDto>>.OK(catalogs);
        }


        /// <summary>
        /// 获取案卷列表
        /// </summary>
        /// <param name="archivesDto">请求参数</param>
        /// <returns></returns>
        [HttpPost("getArchivesList")]
        public BaseResult<List<object>> GetArchivesList([FromBody] ArchivesDto archivesDto)
        {
            using var conn = DbFactory.Db();
            var user = JwtUtils.LoginUser(_accessor.HttpContext);
            //根据fmid获取表关系
            var relation = conn.Query<FormModelTable>("Select * from t_FormModel_Table a where a.FM_ID=@id", new { id = archivesDto.FormModelId }).OrderBy(a => a.FMT_Order).ToList();
            List<object> list = new List<object>();

            //StringBuilder orderBy = new StringBuilder("order by ");
            //获取排序规则

            string orderBy = GetOrderByStr.GetStr(relation.First(a => a.FMT_Order == 0).FMT_ID);
            //点击非叶子节点是否加载子节点数据
            var loadChildData = conn.Query<string>("select Sys_Value from t_SysConfig where Sys_Key='LoadChildsData'").FirstOrDefault();

            String uid = UserPermissionUtil.GetUserPermission(user.U_ID);
            //点击案卷级目录获取relation中的第一个并判断是不是以件归档
            if (relation.Count() > 1 && !relation.First(a => a.FMT_Order == 1).FMT_IsFJ) //案卷列表
            {
                //获取案卷对应的物理表名
                var tableName = conn.QueryFirst<string>("Select a.Table_TableName from t_Table a where a.Table_ID=@id", new { id = relation.First().Table_ID });
                //获取有权限的分类
                string sql =
                    $"select a.* from t_Catalog a left join (select right(GUP_ResourceID, 36) id from T_UserTempMenu where [GU_GUID] in {uid} and MNU_Type = 'Catalog') b on b.id = a.Catalog_ID where a.FM_ID = '{archivesDto.FormModelId}';";
                var authCategories =
                    conn.Query<Catalog>(sql).ToList();
                //判断当前的目录是叶子目录返回加上配置的字段
                if (authCategories.All(a => a.Catalog_Father != archivesDto.CatalogId))
                {
                    string str =
                        $"select top {archivesDto.PageSize} * from(select row_number() over({orderBy}) as rownumber, * from {tableName} where Catalog_ID='{archivesDto.CatalogId}' and Status=9) temp_row where rownumber > (({archivesDto.PageIndex} - 1) * {archivesDto.PageSize});";
                    list = conn.Query<object>(str).ToList();
                }

                //如果没有点击子分类且加载子数据,获取有权限的所有的子分类数据
                if (Guid.Empty != archivesDto.CatalogId && (Convert.ToInt32(loadChildData) == 1||loadChildData==null))
                {
                    string str =
                        $"select top {archivesDto.PageSize} * from(select row_number() over({orderBy}) as rownumber, * from {tableName} a where a.Status=9 and a.Catalog_ID in(select Child_GUID from dbo.GetCatalogChildGUIDs('{archivesDto.CatalogId}'))) temp_row where rownumber > (({archivesDto.PageIndex} - 1) * {archivesDto.PageSize});";
                    list = conn.Query<object>(str).ToList();
                }
            }

            //字段转换
            list = FieldsConvertUtil.ConvertList(list, relation.First().FMT_ID);

            return BaseResult<List<object>>.OK(list);
        }

        /// <summary>
        /// 根据案卷信息获取对应附件或者案卷附件
        /// </summary>
        /// <param name="dto">参数</param>
        /// <returns></returns>
        [HttpPost("getArchivesFileList")]
        public BaseResult<object> GetArchivesFileList([FromBody] ArchivesFileDto dto) //案卷下级
        {
            using var conn = DbFactory.Db();
            var resp = new FileAttachRespDto();
            var user = JwtUtils.LoginUser(_accessor.HttpContext);
            var relation = conn.Query<FormModelTable>("Select * from t_FormModel_Table a where a.FM_ID=@id", new { id = dto.FormModelId }).OrderBy(a => a.FMT_Order).ToList();


            //两级案卷  案卷->件
            if (relation.Count() == 2 && !relation.First(a => a.FMT_Order == 1).FMT_IsFJ && !relation.First(a => a.FMT_Order == 1).FMT_IsAJFJ)
            {
                FormModelTable fjTable = relation.FirstOrDefault(a => a.FMT_Order == 1);
                string orderby = GetOrderByStr.GetStr(fjTable.FMT_ID);
                var tableName = conn.Query<string>("Select a.Table_TableName from t_Table a where a.Table_ID=@id", new { id = fjTable.Table_ID }).First();
                string sql = $"select * from {tableName} where ParentID='{dto.ArchivesId}' and Status=9 {orderby};";
                var list = conn.Query<object>(sql).ToList();
                list = FieldsConvertUtil.ConvertList(list, fjTable.FMT_ID);
                resp.File = list;
            }
            //三级
            else if (relation.Count() == 3)
            {
                //判断是案卷附件
                if (!relation.Any(a => a.FMT_IsFJ))
                {
                    //卷内
                    FormModelTable fileTable = relation.FirstOrDefault(a => a.FMT_IsAJFJ == false && a.FMT_Order > 0);
                    string orderby = GetOrderByStr.GetStr(fileTable.FMT_ID);
                    var fileTableName = conn.Query<string>("Select a.Table_TableName from t_Table a where a.Table_ID=@id", new { id = fileTable.Table_ID }).First();
                    var fileList = conn.Query<object>($"select * from {fileTableName} a where a.ParentID='{dto.ArchivesId}' and a.Status=9 {orderby};").ToList();
                    resp.File = fileList;

                    //案卷附件
                    FormModelTable attachTable = relation.FirstOrDefault(a => a.FMT_IsAJFJ && a.FMT_Order > 0);
                    string attachOrderby = GetOrderByStr.GetStr(attachTable.FMT_ID);
                    var attachTableName = conn.Query<string>("Select a.Table_TableName from t_Table a where a.Table_ID=@id", new { id = attachTable.Table_ID }).First();
                    var attachList = conn.Query<object>($"select * from {attachTableName} a where a.ParentID='{dto.ArchivesId}' and a.Status=9 {attachOrderby};").ToList();
                    attachList = FieldsConvertUtil.ConvertList(attachList, attachTable.FMT_ID);
                    resp.Attach = attachList;
                }

                //判断是卷内附件
                if (!relation.Any(a => a.FMT_IsAJFJ))
                {
                    //卷内
                    FormModelTable fileTable = relation.FirstOrDefault(a => a.FMT_IsFJ == false && a.FMT_Order > 0);
                    String orderby = GetOrderByStr.GetStr(fileTable.FMT_ID);
                    String fileTableName = conn.Query<string>($"Select a.Table_TableName from t_Table a where a.Table_ID='{fileTable.Table_ID}'").First();
                    var fileList = conn.Query<object>($"select * from {fileTableName} a where a.ParentID='{dto.ArchivesId}' and a.Status=9 {orderby};").ToList();
                    fileList = FieldsConvertUtil.ConvertList(fileList, fileTable.FMT_ID);
                    resp.File = fileList.ToList();
                }
            }

            return BaseResult<object>.OK(resp);
        }


        /// <summary>
        /// 根据卷内信息获取卷内附件
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("getFileAttachList")]
        public BaseResult<object> GetFileAttachList([FromBody] FileAttachDto dto)
        {
            using var conn = DbFactory.Db();
            var resp = new FileAttachRespDto();
            var user = JwtUtils.LoginUser(_accessor.HttpContext);
            var relation = conn.Query<FormModelTable>("Select * from t_FormModel_Table a where a.FM_ID=@id", new { id = dto.FormModelId }).OrderBy(a => a.FMT_Order).ToList();
            object obj = new object();
            if (relation.Any(a => a.FMT_IsFJ))
            {
                FormModelTable attachTable = relation.FirstOrDefault(a => a.FMT_IsFJ && a.FMT_Order > 0);
                string attachOrderby = GetOrderByStr.GetStrFileAttachList(attachTable.FMT_ID);
                var attachTableName = conn.Query<string>("Select a.Table_TableName from t_Table a where a.Table_ID=@id", new { id = attachTable.Table_ID }).First();
                var attachList = conn.Query<object>($"select * from {attachTableName} a where a.ParentID='{dto.FileId}' and a.Status=9 {attachOrderby};").ToList();
                attachList = FieldsConvertUtil.ConvertList(attachList, attachTable.FMT_ID);
                obj = attachList;
            }
            return BaseResult<object>.OK(obj);
        }

        /// <summary>
        /// 根据传入信息获取分类下的以件归档信息
        /// </summary>
        /// <param name="dto">参数</param>
        /// <returns></returns>
        [HttpPost("getFileList")]
        public BaseResult<dynamic> GetFileList([FromBody] FileDto dto)
        {
            using var conn = DbFactory.Db();
            var user = JwtUtils.LoginUser(_accessor.HttpContext);
            //根据fmid获取表关系
            var relation = conn.Query<FormModelTable>("Select * from t_FormModel_Table a where a.FM_ID=@id", new { id = dto.FormModelId }).OrderBy(a => a.FMT_Order).ToList();
            List<object> list = new List<object>();



            //点击非叶子节点是否加载子节点数据
            var loadChildData = conn.Query<string>("select Sys_Value from t_SysConfig where Sys_Key='LoadChildsData'").First();


            //点击案卷级目录获取relation中的第一个并判断是不是以件归档
            if (relation.Count == 1 || (relation.Count > 1 && relation.First(a => a.FMT_Order == 1).FMT_IsFJ)) //案卷列表
            {
                string orderBy;
                if (relation.Count != 1)
                {
                    orderBy = GetOrderByStr.GetStr(relation.First(a => a.FMT_IsFJ).FMT_ID);
                }
                else
                {
                    orderBy = GetOrderByStr.GetStr(relation.First().FMT_ID);
                }

                //获取排序规则
                //获取案卷对应的物理表名
                var tableName = conn.QueryFirst<string>("Select a.Table_TableName from t_Table a where a.Table_ID=@id", new { id = relation.First().Table_ID });
                String uid = UserPermissionUtil.GetUserPermission(user.U_ID);
                //获取有权限的分类
                var authCategories =
                    conn.Query<Catalog>(
                        $"select a.*from t_Catalog a left join (select right(GUP_ResourceID, 36) id from T_UserTempMenu where [GU_GUID] in {uid} and MNU_Type = 'Catalog') b on b.id = a.Catalog_ID where a.FM_ID = '{dto.FormModelId}';").ToList();
                //判断当前的目录是叶子目录
                if (authCategories.All(a => a.Catalog_Father != dto.CatalogId))
                {
                    string str =
                        $"select top {dto.PageSize} * from(select row_number() over({orderBy}) as rowNumber, * from {tableName} where Catalog_ID='{dto.CatalogId}' and Status=9) temp_row where rowNumber > (({dto.PageIndex} - 1) * {dto.PageSize});";
                    list = conn.Query<object>(str).ToList();
                }

                //如果没有点击子分类且加载子数据,获取有权限的所有的子分类数据
                if (Guid.Empty != dto.CatalogId && Convert.ToInt32(loadChildData) == 1)
                {
                    string str =
                        $"select top {dto.PageSize} * from(select row_number() over({orderBy}) as rowNumber, * from {tableName} a where a.Status=9 and a.Catalog_ID in(select Child_GUID from dbo.GetCatalogChildGUIDs('{dto.CatalogId}'))) temp_row where rowNumber > (({dto.PageIndex} - 1) * {dto.PageSize});";
                    list = conn.Query<object>(str).ToList();
                }
                //属性转换
                list = FieldsConvertUtil.ConvertList(list, relation.First().FMT_ID);
            }
            else
            {
                string orderBy = GetOrderByStr.GetStr(relation.First(a => a.FMT_Order == 1).FMT_ID);
                //获取排序规则
                //获取案卷对应的物理表名
                var tableName = conn.QueryFirst<string>("Select a.Table_TableName from t_Table a where a.Table_ID=@id", new { id = relation.First(a => a.FMT_Order == 1).Table_ID });
                //获取有权限的分类
                var authCategories =
                    conn.Query<Catalog>(
                        "select a.*from t_Catalog a left join (select right(GUP_ResourceID, 36) id from T_UserTempMenu where [GU_GUID] = @uid and MNU_Type = 'Catalog') b on b.id = a.Catalog_ID where a.FM_ID = @fmid;",
                        new { uid = user.U_ID, fmid = dto.FormModelId }).ToList();
                //判断当前的目录是叶子目录
                if (authCategories.All(a => a.Catalog_Father != dto.CatalogId))
                {
                    string str =
                        $"select top {dto.PageSize} * from(select row_number() over({orderBy}) as rowNumber, * from {tableName} where Catalog_ID='{dto.CatalogId}' and Status=9) temp_row where rowNumber > (({dto.PageIndex} - 1) * {dto.PageSize});";
                    list = conn.Query<object>(str).ToList();
                }

                //如果没有点击子分类且加载子数据,获取有权限的所有的子分类数据
                if (Guid.Empty != dto.CatalogId && Convert.ToInt32(loadChildData) == 1)
                {
                    string str =
                        $"select top {dto.PageSize} * from(select row_number() over({orderBy}) as rowNumber, * from {tableName} a where a.Status=9 and a.Catalog_ID in(select Child_GUID from dbo.GetCatalogChildGUIDs('{dto.CatalogId}'))) temp_row where rowNumber > (({dto.PageIndex} - 1) * {dto.PageSize});";
                    list = conn.Query<object>(str).ToList();
                }
                //属性转换
                list = FieldsConvertUtil.ConvertList(list, relation.First(a => a.FMT_Order == 1).FMT_ID);
            }

            return BaseResult<object>.OK(list);
        }

        /// <summary>
        /// 根据传入id获取全文信息参数
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getAllinfo/{id}")]
        public BaseResult<object> GetAllInfos(Guid id)
        {
            using var conn = DbFactory.Db();
            var user = JwtUtils.LoginUser(_accessor.HttpContext);
            var list = conn.Query<AllInfo>("select * from t_AllInfos a where a.Table_ID=@id", new { id = id }).OrderBy(a => a.AI_Index).ToList();
            if (list.Any())
            {
                //根据t_RelativePath修改AI_SharePath参数
                var path = conn.Query<string>("SELECT Path FROM [dbo].[t_RelativePath] a where a.ID=@rlId and a.IsCurrentPath=1;", new { rlId = list.First().AI_RelativePathGUID });
                foreach (var item in list)
                {
                    item.AI_SharePath = path + item.AI_SharePath;
                }
            }

            return BaseResult<object>.OK(list);
        }

        /// <summary>
        /// 获取表字段值
        /// </summary>
        /// <param name="catalogId">分类id</param>
        /// <param name="formModelId">fmid</param>
        /// <param name="type">类型 0)案卷  1)文件</param>
        /// <returns></returns>
        [HttpGet("getTableFields/{catalogId}/{formModelId}/{type}")]
        public BaseResult<object> GetTableFields(Guid catalogId, Guid formModelId, int type)
        {
            using var conn = DbFactory.Db();
            var user = JwtUtils.LoginUser(_accessor.HttpContext);
            var relation = conn.Query<FormModelTable>("Select * from t_FormModel_Table a where a.FM_ID=@id", new { id = formModelId }).OrderBy(a => a.FMT_Order).ToList();
            //获取有权限的分类
            var authCategories =
                conn.Query<Catalog>(
                    "select a.* from t_Catalog a left join (select right(GUP_ResourceID, 36) id from T_UserTempMenu where [GU_GUID] = @uid and MNU_Type = 'Catalog') b on b.id = a.Catalog_ID where a.FM_ID = @fmid;",
                    new { uid = user.U_ID, fmid = formModelId }).ToList();
            List<TableFieldsDesRespDto> list = new List<TableFieldsDesRespDto>();

            //获取案卷级别的(案卷表数肯定大于等于2并且等于2时没有all isfj==false)
            if (type == 0 && relation.Count > 2 || (relation.Count == 2 && relation.All(a => a.FMT_IsFJ != true)))
            {
                //判断当前分类不是叶子分类
                if (authCategories.Any(a => a.Catalog_Father == catalogId))
                {
                    foreach (var item in relation)
                    {
                        TableFieldsDesRespDto resp = new TableFieldsDesRespDto();
                        var fields = conn.Query<object>(
                                $"SELECT a.*,b.Field_Name from [t_data_disp_mstr] a inner join t_Data_Fields b on a.Field_ID=b.Field_ID  where a.FMT_ID='{item.FMT_ID}' and a.DDM_IsDisplay=1 and a.MY_DisplayFieldValue is null order by a.DDM_Order;")
                            .ToList();
                        resp.Fields = fields;
                        resp.Order = item.FMT_Order;
                        if (item.FMT_IsSmallCatalog)
                        {
                            resp.HasSmallCatalog = true;
                        }

                        if (item.FMT_IsFJ)
                        {
                            resp.IsFJ = true;
                        }

                        if (item.FMT_IsAJFJ)
                        {
                            resp.IsAJFJ = true;
                        }

                        list.Add(resp);
                    }
                }
                //是叶子分类
                else
                {
                    foreach (var item in relation)
                    {
                        TableFieldsDesRespDto resp = new TableFieldsDesRespDto();
                        var fields = conn.Query<object>(
                                $"SELECT a.*,b.Field_Name from [t_data_disp_mstr] a inner join t_Data_Fields b on a.Field_ID=b.Field_ID  where a.FMT_ID='{item.FMT_ID}' and a.DDM_IsDisplay=1  and a.MY_DisplayFieldValue is null or (a.MY_DisplayFieldValue is not null and a.MY_DisplayFieldValue like('%{catalogId}%'))  order by a.DDM_Order;")
                            .ToList();
                        resp.Fields = fields;
                        resp.Order = item.FMT_Order;
                        if (item.FMT_IsSmallCatalog)
                        {
                            resp.HasSmallCatalog = true;
                        }

                        if (item.FMT_IsFJ)
                        {
                            resp.IsFJ = true;
                        }

                        if (item.FMT_IsAJFJ)
                        {
                            resp.IsAJFJ = true;
                        }

                        list.Add(resp);
                    }
                }
            }
            //获取文件级别的
            else
            {
                if (relation.Count == 1)
                {
                }
                else if (relation.Count == 2)
                {
                    if (!relation.Any(a => a.FMT_IsFJ))
                    {
                        relation.Remove(relation.First(a => a.FMT_Order == 0));
                    }
                }
                else
                {
                    relation.RemoveAt(0);
                    if (relation.Any(a => a.FMT_IsAJFJ))
                    {
                        relation.Remove(relation.First(a => a.FMT_IsAJFJ));
                    }
                }

                //判断当前分类不是叶子分类
                if (authCategories.Any(a => a.Catalog_Father == catalogId))
                {
                    foreach (var item in relation)
                    {
                        TableFieldsDesRespDto resp = new TableFieldsDesRespDto();
                        var fields = conn.Query<object>(
                                $"SELECT a.*,b.Field_Name from [t_data_disp_mstr] a inner join t_Data_Fields b on a.Field_ID=b.Field_ID  where a.FMT_ID='{item.FMT_ID}' and a.DDM_IsDisplay=1 and a.MY_DisplayFieldValue is null order by a.DDM_Order;")
                            .ToList();
                        resp.Fields = fields;
                        resp.Order = item.FMT_Order;
                        if (item.FMT_IsSmallCatalog)
                        {
                            resp.HasSmallCatalog = true;
                        }

                        if (item.FMT_IsFJ)
                        {
                            resp.IsFJ = true;
                        }

                        if (item.FMT_IsAJFJ)
                        {
                            resp.IsAJFJ = true;
                        }

                        list.Add(resp);
                    }
                }
                //是叶子分类
                else
                {
                    foreach (var item in relation)
                    {
                        TableFieldsDesRespDto resp = new TableFieldsDesRespDto();
                        var fields = conn.Query<object>(
                                $"SELECT a.*,b.Field_Name from [t_data_disp_mstr] a inner join t_Data_Fields b on a.Field_ID=b.Field_ID  where a.FMT_ID='{item.FMT_ID}' and a.DDM_IsDisplay=1  and a.MY_DisplayFieldValue is null or (a.MY_DisplayFieldValue is not null and a.MY_DisplayFieldValue like('%{catalogId}%'))  order by a.DDM_Order;")
                            .ToList();
                        resp.Fields = fields;
                        resp.Order = item.FMT_Order;
                        if (item.FMT_IsSmallCatalog)
                        {
                            resp.HasSmallCatalog = true;
                        }

                        if (item.FMT_IsFJ)
                        {
                            resp.IsFJ = true;
                        }

                        if (item.FMT_IsAJFJ)
                        {
                            resp.IsAJFJ = true;
                        }

                        list.Add(resp);
                    }
                }
            }

            return BaseResult<object>.OK(list);
        }

        /// <summary>
        /// 获取小分类列表
        /// </summary>
        /// <param name="formModelId"></param>
        /// <returns></returns>
        [HttpGet("getSmallCatalog/{formModelId}")]
        public BaseResult<List<SmallCatalogDto>> GetSmallCatalog(Guid formModelId)
        {
            using var conn = DbFactory.Db();
            var user = JwtUtils.LoginUser(_accessor.HttpContext);
            List<FormModelTable> relation = conn.Query<FormModelTable>("Select * from t_FormModel_Table a where a.FM_ID=@id", new { id = formModelId }).OrderBy(a => a.FMT_Order)
                .ToList();
            List<SmallCatalogDto> dto = new List<SmallCatalogDto>();
            if (relation.Any(a => a.FMT_IsSmallCatalog))
            {
                var list = conn.Query<SmallCatalog>($"select * from t_SmallCatalog where FM_ID='{formModelId}';").OrderBy(a => a.Catalog_Order).ToList();
                dto = RecursiveUtil.GetSmallCatalogDto(list);
            }

            return BaseResult<List<SmallCatalogDto>>.OK(dto);
        }

        /// <summary>
        /// 获取搜索结果数
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet("searchContentsCount")]
        public BaseResult<object> SearchContentsCount(string key)
        {
            using var conn = DbFactory.Db();
            var user = JwtUtils.LoginUser(_accessor.HttpContext);

            List<string> tempGroup = new List<string>();
            tempGroup.Add(user.U_ID.ToString());
            string gid = conn.QueryFirstOrDefault<string>($"select * from t_Group_User where U_ID='{user.U_ID}'");
            string mSearchPower = conn.ExecuteScalar("select Sys_Value from t_SysConfig where Sys_Key='MSearchPower'").ToString();
            if (string.IsNullOrEmpty(gid))
            {
                tempGroup.Add(gid);
            }
            string[] tempStrList;
            tempStrList = !string.IsNullOrEmpty(key) ? key.Split(' ').ToArray() : new string[] { "" };

            string likeSqlStr = "";
            foreach (string s in tempStrList.Distinct())
            {
                if (s.Trim() != "")
                {
                    likeSqlStr = likeSqlStr + " and SearchContent like '%" + s + "%'";
                }
            }

            string sql;
            string uid = string.Join("','", tempGroup.ToArray());
            if (string.IsNullOrEmpty(key))
            {
                sql = "select Count(*) as DataCount from t_SearchContents";
            }
            else if (mSearchPower != null && mSearchPower == "YES")
            {
                sql = "select Count(*) as DataCount from t_SearchContents where Catalog_GUID in( select right(GUP_ResourceID,36) from T_UserTempMenu where GU_GUID in ('" + uid +
                      "') and MNU_Type='Catalog')" + likeSqlStr;
            }
            else
            {
                sql = "select Count(*) as DataCount from t_SearchContents where " + likeSqlStr.Substring(4, likeSqlStr.Length - 4);
            }

            int count = conn.QueryFirst<int>(sql);
            return BaseResult<object>.OK(count);
        }

        /// <summary>
        /// 获取搜索结果
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("getAllSearchData")]
        public BaseResult<object> GetAllSearchData(SearchContentDto dto)
        {
            using var conn = DbFactory.Db();
            var user = JwtUtils.LoginUser(_accessor.HttpContext);
            bool IsManager = user.U_IsManager;
            int currPage = dto.PageIndex;
            int PageSize = dto.PageSize;
            List<string> tempGroup = new List<string>();
            tempGroup.Add(user.U_ID.ToString());
            string gid = conn.QueryFirstOrDefault<string>($"select * from t_Group_User where U_ID='{user.U_ID}'");
            string mSearchPower = conn.ExecuteScalar("select Sys_Value from t_SysConfig where Sys_Key='MSearchPower'").ToString();
            if (string.IsNullOrEmpty(gid))
            {
                tempGroup.Add(gid);
            }

            String[] tempStrList = dto.Key.Split(' ').ToArray();
            String likeSqlStr = "";
            String likeSqlStrOcr = "";
            String tempSqlOcrStr = "";
            foreach (string s in tempStrList.Distinct())
            {
                if (s.Trim() != "")
                {
                    likeSqlStr = likeSqlStr + " and SearchContent like '%" + s + "%'";
                }
            }

            string sql;
            string uid = string.Join("','", tempGroup.ToArray());
            foreach (string s in tempStrList.Distinct())
            {
                if (s.Trim() == "") continue;
                likeSqlStr = likeSqlStr + " and SearchContent like '%" + s + "%'";
                if (dto.IsQwSearch)
                    likeSqlStrOcr = likeSqlStrOcr + " and OCRContents like '%" + s + "%'";
            }
            if (dto.IsQwSearch && likeSqlStrOcr != "")
            {
                tempSqlOcrStr = "Select distinct Record_GUID from t_searchOcr where " + likeSqlStrOcr.Substring(4, likeSqlStrOcr.Length - 4);
            }

            if (mSearchPower != null && mSearchPower.ToUpper() == "YES")
            {
                if (!IsManager)
                {
                    if (dto.Key == "" || dto.Key == null)
                    {
                        sql = "select* from(select row_number() over(order by Record_DateTime) as rowNum, *from t_SearchContents where Catalog_GUID in(select right(GUP_ResourceID, 36) from T_UserTempMenu where GU_GUID in ('" + uid + "') and MNU_Type = 'Catalog')) tempSearch where rowNum between " + ((currPage * PageSize) + 1) + " and " + ((currPage * PageSize) + PageSize) + "";
                    }
                    else
                    {
                        if (dto.IsQwSearch)
                        {
                            sql = "select * from (select row_number() over(order by Record_DateTime) as rowNum, * from t_SearchContents where Catalog_GUID in( select right(GUP_ResourceID,36) from T_UserTempMenu where GU_GUID in ('" + uid + "') and MNU_Type='Catalog')" + likeSqlStr + " or Record_GUID in (" + tempSqlOcrStr + ")) tempSearch where rowNum between " + ((currPage * PageSize) + 1) + " and " + ((currPage * PageSize) + PageSize) + "";
                        }
                        else
                        {
                            sql = "select * from (select row_number() over(order by Record_DateTime) as rowNum, * from t_SearchContents where Catalog_GUID in( select right(GUP_ResourceID,36) from T_UserTempMenu where GU_GUID in ('" + uid + "') and MNU_Type='Catalog')" + likeSqlStr + ") tempSearch where rowNum between " + ((currPage * PageSize) + 1) + " and " + ((currPage * PageSize) + PageSize) + "";
                        }
                    }
                }
                else
                {
                    if (dto.Key == "" || dto.Key == null)
                    {
                        sql = "select * from (select row_number() over(order by Record_DateTime) as rowNum,* from t_SearchContents) tempSearch where rowNum between " + (currPage * PageSize + 1) + " and " + ((currPage * PageSize) + PageSize) + "";
                    }
                    else
                    {
                        if (dto.IsQwSearch)
                        {
                            sql = "select * from (select row_number() over(order by Record_DateTime) as rowNum, * from t_SearchContents where " + likeSqlStr.Substring(4, likeSqlStr.Length - 4) + " or Record_GUID in (" + tempSqlOcrStr + ")) tempSearch where rowNum between " + (currPage * PageSize + 1) + " and " + (currPage * PageSize + PageSize) + "";
                        }
                        else
                        {
                            sql = "select * from (select row_number() over(order by Record_DateTime) as rowNum, * from t_SearchContents where " + likeSqlStr.Substring(4, likeSqlStr.Length - 4) + ") tempSearch where rowNum between " + (currPage * PageSize + 1) + " and " + (currPage * PageSize + PageSize) + "";
                        }
                    }
                }
            }
            else
            {
                if (dto.Key == "" || dto.Key == null)
                {
                    sql = "select * from (select row_number() over(order by Record_DateTime) as rowNum,* from t_SearchContents) tempSearch where rowNum between " + (currPage * PageSize + 1) + " and " + ((currPage * PageSize) + PageSize) + "";
                }
                else
                {
                    if (dto.IsQwSearch)
                    {
                        sql = "select * from (select row_number() over(order by Record_DateTime) as rowNum, * from t_SearchContents where " + likeSqlStr.Substring(4, likeSqlStr.Length - 4) + " or Record_GUID in (" + tempSqlOcrStr + ")) tempSearch where rowNum between " + (currPage * PageSize + 1) + " and " + (currPage * PageSize + PageSize) + "";
                    }
                    else
                    {
                        sql = "select * from (select row_number() over(order by Record_DateTime) as rowNum, * from t_SearchContents where " + likeSqlStr.Substring(4, likeSqlStr.Length - 4) + ") tempSearch where rowNum between " + (currPage * PageSize + 1) + " and " + (currPage * PageSize + PageSize) + "";
                    }
                }
            }

            var list = conn.Query<object>(sql).ToList();
            return BaseResult<object>.OK(list);
        }

        /// <summary>
        /// 获取搜索卷内
        /// </summary>
        /// <param name="parentID">id</param>
        /// <returns></returns>
        [HttpGet("GetAllSearchData_JN/{parentID}")]
        public BaseResult<object> GetAllSearchData_JN(Guid parentID)
        {
            using var conn = DbFactory.Db();
            var user = JwtUtils.LoginUser(_accessor.HttpContext);
            string sql;
            sql = $"select * from t_SearchContents where ParentID='{parentID}'";

            var list = conn.Query<object>(sql).ToList();
            return BaseResult<object>.OK(list);
        }
    }
}